package cn.edu.gzist.chapter07.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

// @Service
public class MyUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // User userDO = userService.getByUsername(username);
        // if (userDO == null){
        // throw new UsernameNotFoundException("用户不存在！");
        // }
        System.out.println(username);
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        if ("admin".equals(username)) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }

        // 加密
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String rawPassword = "123456";
        String encodedPassword = encoder.encode(rawPassword);
        System.out.println(encodedPassword);
        return new org.springframework.security.core.userdetails.User(username, encodedPassword,
                simpleGrantedAuthorities);
    }

}
